C++ 内联方法、异常处理
内联方法
使用
inline关键字定义修饰方法编译器在编译代码时,会把这类方法体放置到调用者的方法内,以提高性能
```c++
inline void print(string& str) {//}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
### 异常处理
[异常类型查询](https://en.cppreference.com/w/cpp/error/exception)
- 抛异常和 JS 类似,`throw xx_error("..")`
- 处理异常使用 `try {} catch (const std::exception& ex) {}`
- 一个 try 代码块可以对应多个 catch 代码块,用于捕获多种不同类型的异常
- ```c++
try
{
phoneNum = getPhoneNum();
}
catch (const std::exception& ex) //接收exception类型的异常
{
cout << ex.what() << endl; //打印异常信息信息
return 0;
}
catch (const string& ex) //接收字符串类型的异常
{
cout << ex << endl; //打印异常信息信息
return 0;
}
catch (...) { //所有其他类型的异常
cout << "undefinde Error" << endl; //打印异常信息信息
}可以抛出自定义错误类型,但需要对应类型的 catch 捕获
如果被标记了 noexcept 的方法抛出了异常,那么 C++ 将调用 terminate() 方法终止应用程序
string getPhoneNum() noexcept{ //... }
try catch 可以捕获深度嵌套的异常(多少层都可以)